/*
 * File     : MethodSortingVisitor.java
 * Created  : 9 Oct 2011
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.structure;

import static com.googlecode.dni.internal.DniInternal.LOGGER;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

import com.googlecode.dni.type.structure.Structure;

/**
 * Sorts methods by their definition in a class file.  Used because Java
 * annoyingly reorders methods.
 *
 * @author Matthew Wilson
 */
final class MethodSortingVisitor extends ClassVisitor
{

    private static final Set< String > IGNORED_NAMES = new HashSet< String >( Arrays.asList( "<init>", "<clinit>", "equals", "hashCode", "toString" ) );

    private final List< Method > methods = new ArrayList< Method >();

    private final List< Method > sortedMethods = new ArrayList< Method >();

    private boolean discrepancy;

    private String typedName;


    /**
     * @param methods
     *            the unsorted methods
     */
    MethodSortingVisitor( final Method[] methods )
    {
        super( Opcodes.ASM4 );

        for ( Method method : methods )
        {
            Class< ? > declaringClass = method.getDeclaringClass();
            if ( declaringClass != Structure.class && Structure.class.isAssignableFrom( declaringClass ) )
            {
                this.methods.add( method );
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void visit( final int version,
                       final int access,
                       final String name,
                       final String signature,
                       final String superName,
                       final String[] interfaces )
    {
        this.typedName = name;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void visitSource( final String source, final String debug )
    {
        // don't care
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void visitOuterClass( final String owner, final String name, final String desc )
    {
        // don't care
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public AnnotationVisitor visitAnnotation( final String desc, final boolean visible )
    {
        // don't care
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void visitAttribute( final Attribute attr )
    {
        // don't care
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void visitInnerClass( final String name, final String outerName, final String innerName, final int access )
    {
        // don't care
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public FieldVisitor visitField( final int access,
                                    final String name,
                                    final String desc,
                                    final String signature,
                                    final Object value )
    {
        // don't care
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public MethodVisitor visitMethod( final int access,
                                      final String name,
                                      final String desc,
                                      final String signature,
                                      final String[] exceptions )
    {
        if ( IGNORED_NAMES.contains( name ) )
        {
            return null;
        }

        Method method = null;
        for ( Iterator< Method > iterator = this.methods.iterator(); iterator.hasNext(); )
        {
            Method candidate = iterator.next();
            if ( candidate.getName().equals( name ) )
            {
                // no overloaded methods are supported by Structure, so it's
                // safe just to check the name
                method = candidate;
                iterator.remove();
                break;
            }
        }

        if ( method == null )
        {
            this.discrepancy = true;
        }
        else
        {
            this.sortedMethods.add( method );
        }

        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void visitEnd()
    {
        // don't care
    }

    /**
     * @return the sorted methods
     */
    List< Method > getSortedMethods()
    {
        if ( this.discrepancy || !this.methods.isEmpty() )
        {
            LOGGER.warning( "Discrepancy between class file and loaded class: " + this.typedName );
        }

        return this.sortedMethods;
    }

}
